layui.extend({
    dtree: '{/}static/layui_ext/dtree/dtree'   // {/}的意思即代表采用自有路径，即不跟随 base 路径
}).use(['dtree','layer','jquery'], function() {
    var tableData = {};
    var repId = 0;
    var treeId = 0;
    var dtree = layui.dtree, layer = layui.layer;
    var spoonUrl = null;
    $('#repSelect').on('change', function(){
        repId=$("#repSelect").val();
        if(repId == '0'){
            return;
        }
        renderTree();
        getSpoonUrl();
    });

    function getSpoonUrl() {
        $.ajax({
            type: "get",
            url: base_url + "/dataCollection/dicategory/findRepositoryById?id=" + repId,
            cache: false,
            success: function (redata) {
                let kettleInfo = redata.result;
                //?rep=kettle_rep&KUser=admin&pass=0717&trans=273
                spoonUrl = kettleInfo.url + '?rep=' + kettleInfo.repName + '&user='
                    + kettleInfo.repUsername + '&pass=' + kettleInfo.repPassword;
            }
        });
    }

    function getTreeData(){
        var treeData = [];
        $.ajax({
            url: base_url + "/dataCollection/dicategory/findDiCateryByRep?id=" + repId ,
            async: false,
            type: 'GET',
            success: function (data) {
                if (data.code == "200") {
                    var redata = data.result == null ? [] : data.result;
                    treeData = toTree(redata);

                } else {
                    treeData = [];
                    repId = 0;
                    treeId = 0;
                    jobTable.fnDraw();
                }

            }
        })
        return treeData;
        // $.get(base_url + "/dataCollection/dicategory/findDiCateryByRep?id=" + repId , function(data, status) {
        //
        // });
    };
    function renderTree(){

        var data = getTreeData();
        var DemoTree = dtree.render({
            elem: "#ODSmenuTree",
            data: data, // 使用data加载
            type: 'load',
            toolbar: true,
            toolbarWay: "follow", //follow
            toolbarShow: [],
            toolbarExt:     [
                {
                    toolbarId: "testEdit",
                    icon: "dtree-icon-bianji",
                    title: "编辑节点",
                    handler: function (node, $div) {
                        $("#updateDirModal .form input[name='name']").val( node.context );
                        $("#updateDirModal .form input[name='dirId']").val( node.nodeId );
                        $("#updateDirModal .form input[name='repId']").val( repId );

                        $('#updateDirModal').modal({backdrop: false, keyboard: false}).modal('show');
                    }
                },
                {
                    toolbarId: "testDel",
                    icon: "dtree-icon-roundclose",
                    title: "删除节点",
                    handler: function (node, $div) {
                        var msg = '确定删除' + node.context + '节点吗？';
                        layer.confirm(msg, {
                            title: '提示'
                        }, function (index) {
                            $.ajax({
                                type: "get",
                                url: base_url + "/dataCollection/dicategory/delete?dirId=" + node.nodeId + '&repId=' + repId,
                                dataType: 'json',
                                cache: false,
                                contentType: "application/json",
                                success: function (redata) {
                                    renderTree();
                                    layer.close(index);
                                }
                            });
                        });
                    }
                }
            ],
            // url: "../json/case/demoJson.json" // 使用url加载（可与data加载同时存在）
        });
        // 绑定节点点击
        dtree.on("node('ODSmenuTree')" ,function(obj){
            var param = obj.param;
            treeId = param.nodeId;
            jobTable.fnDraw();
        });
    }

// init date tables
    var jobTable = $("#job_fileDir_list").dataTable({
        "deferRender": true,
        "processing" : true,
        "serverSide": true,
        "ajax": {
            url: base_url + "/dataCollection/discript/findDiScriptById",
            type:"get",
            data : function ( d ) {
                var obj = {};
                obj.page = d.start;
                obj.limit = d.length;
                obj.id=treeId;
                obj.repId=repId;
                return obj;
            }
        },
        "searching": false,
        "ordering": false,
        //"scrollX": true,	// scroll x，close self-adaption
        "columns": [
            {
                "data": 'id',
                "bSortable": false,
                "visible" : false,
                "width":'7%'
            },
            {
                "data": 'text',
                "visible" : true,
                "width":'25%'
            },
            {
                "data": 'extra',
                "visible" : true,
                "width":'25%'
            },
            {
                "data": 'objectType',
                "visible" : true,
                "width":'25%'
            },
            {
                "data": I18n.system_opt,
                "width":'15%',
                "render": function ( data, type, row ) {
                    return function(){
                        // data
                        tableData['key'+row.id] = row;

                        // opt
                        var html = '<div class="btn-group">\n' +
                            '     <button type="button" class="btn btn-primary btn-sm">'+ I18n.system_opt +'</button>\n' +
                            '     <button type="button" class="btn btn-primary btn-sm dropdown-toggle" data-toggle="dropdown">\n' +
                            '       <span class="caret"></span>\n' +
                            '       <span class="sr-only">Toggle Dropdown</span>\n' +
                            '     </button>\n' +
                            '     <ul class="dropdown-menu" role="menu" _id="'+ row.id +'" >\n' +
                            '       <li><a href="javascript:void(0);" class="opt_rename" >'+ '重命名' +'</a></li>\n' +
                            '       <li><a href="javascript:void(0);" class="opt_edit" >'+ I18n.system_opt_edit +'</a></li>\n' +
                            '       <li><a href="javascript:void(0);" class="opt_del" >'+ I18n.system_opt_del +'</a></li>\n' +
                            '     </ul>\n' +
                            '   </div>';

                        return html;
                    };
                }
            }
        ],
        "language" : {
            "sProcessing" : I18n.dataTable_sProcessing ,
            "sLengthMenu" : I18n.dataTable_sLengthMenu ,
            "sZeroRecords" : I18n.dataTable_sZeroRecords ,
            "sInfo" : I18n.dataTable_sInfo ,
            "sInfoEmpty" : I18n.dataTable_sInfoEmpty ,
            "sInfoFiltered" : I18n.dataTable_sInfoFiltered ,
            "sInfoPostFix" : "",
            "sSearch" : I18n.dataTable_sSearch ,
            "sUrl" : "",
            "sEmptyTable" : I18n.dataTable_sEmptyTable ,
            "sLoadingRecords" : I18n.dataTable_sLoadingRecords ,
            "sInfoThousands" : ",",
            "oPaginate" : {
                "sFirst" : I18n.dataTable_sFirst ,
                "sPrevious" : I18n.dataTable_sPrevious ,
                "sNext" : I18n.dataTable_sNext ,
                "sLast" : I18n.dataTable_sLast
            },
            "oAria" : {
                "sSortAscending" : I18n.dataTable_sSortAscending ,
                "sSortDescending" : I18n.dataTable_sSortDescending
            }
        }
    });
    /**
     * 生成树
     * @param data
     * @returns {[]}
     */
    function toTree(data) { // 删除 所有 children,以防止多次调用
        data.forEach(function (item) {
            delete item.children;
        }); // 将数据存储为 以 id 为 KEY 的 map 索引数据列
        var map = {};
        data.forEach(function (item) {
            item.label = item.id;
            item.title = item.text;
            item.spread = false;
            map[item.id] = item;
        });
        var val = [];
        data.forEach(function (item) { // 以当前遍历项，的pid,去map对象中找到索引的id
            var parent = map[item.pid]; // 如果找到索引，那么说明此项不在顶级当中,那么需要把此项添加到，他对应的父级中
            if (parent) {
                (parent.children || (parent.children = [])).push(item);
            } else { //如果没有在map中找到对应的索引ID,那么直接把 当前的item添加到 val结果集中，作为顶级
                val.push(item);
            }
        });
        return val;
    }

    $('#addDir').on('click', function(){
        if(repId == '0'){
            layer.open({
                title: I18n.system_tips,
                btn: [ I18n.system_ok ],
                content: '请先选择资源库',
                icon: '2'
            })
            return;
        }
        // $("#addModal .form input[name='cronConf']").cronGen({});
        $('#addDirModal').modal({backdrop: false, keyboard: false}).modal('show');
    });
    var icon = "<i class='fa fa-times-circle'></i> ";
    var addModalValidate = $("#addDirModal .form").validate({
        errorElement : 'span',
        errorClass : 'help-block',
        focusInvalid : true,
        rules: {
            name: {
                required: true
            }
        },
        messages: {
            name: {
                required: icon + "请输入目录名称"
            }
        },
        highlight : function(element) {
            $(element).closest('.form-group').addClass('has-error');
        },
        success : function(label) {
            label.closest('.form-group').removeClass('has-error');
            label.remove();
        },
        errorPlacement : function(error, element) {
            element.parent('div').append(error);
        },
        submitHandler : function(form) {
            $("#addDirModal .form input[name='dirId']").val(treeId);
            $("#addDirModal .form input[name='repId']").val(repId);
            $.ajax({
                url: base_url + "/dataCollection/dicategory/add",
                type: 'POST',
                cache: false,
                data: $("#addDirModal .form").serialize(),
                dataType: "json",
                success: function(data){
                    if (data.code == "200") {
                        $('#addDirModal').modal('hide');
                        layer.open({
                            title: I18n.system_tips ,
                            btn: [ I18n.system_ok ],
                            content: I18n.system_add_suc ,
                            icon: '1',
                            end: function(layero, index){
                                renderTree();
                            }
                        });
                    } else {
                        layer.open({
                            title: I18n.system_tips,
                            btn: [ I18n.system_ok ],
                            content: (data.message || I18n.system_add_fail  ),
                            icon: '2'
                        });
                    }
                }
            });
            // $.post(base_url + "/dataCollection/dicategory/add",  $("#addDirModal .form").serialize(), function(data, status) {
            //
            // });
        }
    });
    $("#addDirModal").on('hide.bs.modal', function () {
        $("#addDirModal .form")[0].reset();
        addModalValidate.resetForm();
        $("#addDirModal .form .form-group").removeClass("has-error");
    });


    $('#addScript').on('click', function(){
        if(repId == '0'){
            layer.open({
                title: I18n.system_tips,
                btn: [ I18n.system_ok ],
                content: '请先选择资源库',
                icon: '2'
            })
            return;
        }
        // $("#addModal .form input[name='cronConf']").cronGen({});
        $('#addScriptModal').modal({backdrop: false, keyboard: false}).modal('show');
    });
    var addModalValidate2 = $("#addScriptModal .form").validate({
        errorElement : 'span',
        errorClass : 'help-block',
        focusInvalid : true,
        rules: {
            name: {
                required: true
            }
        },
        messages: {
            name: {
                required: icon + "请输入脚本名称"
            }
        },
        highlight : function(element) {
            $(element).closest('.form-group').addClass('has-error');
        },
        success : function(label) {
            label.closest('.form-group').removeClass('has-error');
            label.remove();
        },
        errorPlacement : function(error, element) {
            element.parent('div').append(error);
        },
        submitHandler : function(form) {
            $("#addScriptModal .form input[name='dirId']").val(treeId);
            $("#addScriptModal .form input[name='repId']").val(repId);
            $.ajax({
                url: base_url + "/dataCollection/discript/add",
                type: 'POST',
                cache: false,
                data: $("#addScriptModal .form").serialize(),
                dataType: "json",
                success: function(data){
                    if (data.code == "200") {
                        $('#addScriptModal').modal('hide');
                        layer.open({
                            title: I18n.system_tips ,
                            btn: [ I18n.system_ok ],
                            content: I18n.system_add_suc ,
                            icon: '1',
                            end: function(layero, index){
                                jobTable.fnDraw();
                                // openWebSpoon(spoonUrl, $("#addScriptModal .form input[name='scriptId']").val(), $("#addScriptModal .form input[name='type']").val() == 'job'?'0':'1');
                            }
                        });
                    } else {
                        layer.open({
                            title: I18n.system_tips,
                            btn: [ I18n.system_ok ],
                            content: (data.message || I18n.system_add_fail  ),
                            icon: '2'
                        });
                    }
                }
            });
            // $.post(base_url + "/dataCollection/dicategory/add",  $("#addDirModal .form").serialize(), function(data, status) {
            //
            // });
        }
    });
    $("#addScriptModal").on('hide.bs.modal', function () {
        $("#addScriptModal .form")[0].reset();
        addModalValidate2.resetForm();
        $("#addScriptModal .form .form-group").removeClass("has-error");
    });


    var updateModalValidate = $("#updateDirModal .form").validate({
        errorElement : 'span',
        errorClass : 'help-block',
        focusInvalid : true,
        rules: {
            name: {
                required: true
            }
        },
        messages: {
            name: {
                required: icon + "请输入目录名称"
            }
        },
        highlight : function(element) {
            $(element).closest('.form-group').addClass('has-error');
        },
        success : function(label) {
            label.closest('.form-group').removeClass('has-error');
            label.remove();
        },
        errorPlacement : function(error, element) {
            element.parent('div').append(error);
        },
        submitHandler : function(form) {
            $.post(base_url + "/dataCollection/dicategory/update",  $("#updateDirModal .form").serialize(), function(data, status) {
                if (data.code == "200") {
                    $('#updateDirModal').modal('hide');

                    layer.open({
                        title: I18n.system_tips ,
                        btn: [ I18n.system_ok ],
                        content: I18n.system_update_suc ,
                        icon: '1',
                        end: function(layero, index){
                            renderTree();
                        }
                    });
                } else {
                    layer.open({
                        title: I18n.system_tips,
                        btn: [ I18n.system_ok ],
                        content: (data.message || I18n.system_update_fail  ),
                        icon: '2'
                    });
                }
            });
        }
    });
    $("#updateDirModal").on('hide.bs.modal', function () {
        $("#updateDirModal .form")[0].reset();
        updateModalValidate.resetForm();
        $("#updateDirModal .form .form-group").removeClass("has-error");
    });


    $("#job_fileDir_list").on('click', '.opt_rename',function() {

        var id = $(this).parents('ul').attr("_id");
        var row = tableData['key' + id];

        var script = row.id.split('@');
        var scriptId = script.pop();
        console.log(11111222, row, scriptId);
        $("#updateScriptModal .form input[name='dirId']").val( treeId );
        $("#updateScriptModal .form input[name='name']").val( row.text );
        $("#updateScriptModal .form input[name='repId']").val( repId );
        $("#updateScriptModal .form input[name='scriptId']").val( scriptId );
        $("#updateScriptModal .form input[name='type']").val( row.objectType == 'job'?'0':'1' );
        $('#updateScriptModal').modal({backdrop: false, keyboard: false}).modal('show');
    });

    var updateModalValidate2 = $("#updateScriptModal .form").validate({
        errorElement : 'span',
        errorClass : 'help-block',
        focusInvalid : true,
        rules: {
            name: {
                required: true
            }
        },
        messages: {
            name: {
                required: icon + "请输入目录名称"
            }
        },
        highlight : function(element) {
            $(element).closest('.form-group').addClass('has-error');
        },
        success : function(label) {
            label.closest('.form-group').removeClass('has-error');
            label.remove();
        },
        errorPlacement : function(error, element) {
            element.parent('div').append(error);
        },
        submitHandler : function(form) {
            $.post(base_url + "/dataCollection/discript/update",  $("#updateScriptModal .form").serialize(), function(data, status) {
                if (data.code == "200") {
                    $('#updateScriptModal').modal('hide');

                    layer.open({
                        title: I18n.system_tips ,
                        btn: [ I18n.system_ok ],
                        content: I18n.system_update_suc ,
                        icon: '1',
                        end: function(layero, index){
                            jobTable.fnDraw();
                        }
                    });
                } else {
                    layer.open({
                        title: I18n.system_tips,
                        btn: [ I18n.system_ok ],
                        content: (data.message || I18n.system_update_fail  ),
                        icon: '2'
                    });
                }
            });
        }
    });
    $("#updateScriptModal").on('hide.bs.modal', function () {
        $("#updateScriptModal .form")[0].reset();
        updateModalValidate2.resetForm();
        $("#updateScriptModal .form .form-group").removeClass("has-error");
    });

    // opt_del
    $("#job_fileDir_list").on('click', '.opt_del',function() {
        var id = $(this).parents('ul').attr("_id");
        var row = tableData['key' + id];
        var script = row.id.split('@');
        var scriptId = script.pop();
        layer.confirm( (I18n.system_ok + "删除此脚本吗？") , {
            icon: 3,
            title: I18n.system_tips ,
            btn: [ I18n.system_ok, I18n.system_cancel ]
        }, function(index){
            layer.close(index);

            $.ajax({
                type : 'get',
                url : base_url + '/dataCollection/discript/delete',
                data : {"id":scriptId, 'type': row.objectType == 'job'?'0':'1', 'repId': repId},
                dataType : "json",
                success : function(data){
                    if (data.code == 200) {
                        layer.open({
                            title: I18n.system_tips ,
                            btn: [ I18n.system_ok ],
                            content: ("删除脚本" + I18n.system_success),
                            icon: '1',
                            end: function(layero, index){
                                jobTable.fnDraw();
                            }
                        });
                    } else {
                        layer.open({
                            title: I18n.system_tips,
                            btn: [ I18n.system_ok ],
                            content: (data.message || ("删除脚本" + I18n.system_fail)),
                            icon: '2'
                        });
                    }
                },
            });
        });
    });

    function openWebSpoon(kettleUrlNoKtrId,scriptid,type){
        if (scriptid != null && spoonUrl!=null) {
            var url = 'http://' + kettleUrlNoKtrId;
            if (type == '1') {
                url = url + '&trans=' + scriptid;
            } else {
                url = url + '&job=' + scriptid;
            }
            window.open(url);
        }
    }

    // opt_edit
    $("#job_fileDir_list").on('click', '.opt_edit',function() {
        console.log("123");
        var id = $(this).parents('ul').attr("_id");
        var row = tableData['key' + id];
        var script = row.id.split('@');
        var scriptId = script.pop();
        openWebSpoon(spoonUrl, scriptId, row.objectType == 'job'?'0':'1');
    });
});